using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Xml;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.DALC
{
    public class JobInstructionDALC
    {
        public static string GetJobInstruction(Guid jobID)
        {
            string xml = string.Empty;
            string connStr = ConfigurationManager.ConnectionStrings["Workflow"].ConnectionString;
            SqlConnection conn = new SqlConnection(connStr);
            try
            {
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "GetJobInstruction";
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter jobIDParam = new SqlParameter("@JobID", jobID.ToString());
                cmd.Parameters.Add(jobIDParam);
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    xml = reader["Xdoc"].ToString();
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandlesException(ex);
            }
            finally
            {
                conn.Close();
            }
            return xml;
        }

        public static void SaveJobInstruction(InstructionBase instruction)
        {
            string connStr = ConfigurationManager.ConnectionStrings["Workflow"].ConnectionString;
            SqlConnection conn = new SqlConnection(connStr);
            try
            {
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "SaveJobInstruction";
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter jobIDParam = new SqlParameter("@JobID", instruction.OwnerWorkerInstanceID.ToString());
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml("<Instructions></Instructions>");
                XmlNode root = xdoc.DocumentElement;
                instruction.Serialize(ref xdoc, ref root);
                SqlParameter xdocParam = new SqlParameter("@Xdoc", xdoc.OuterXml);
                cmd.Parameters.AddRange(new SqlParameter[] { jobIDParam, xdocParam });
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandlesException(ex);
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
